# -*- coding: utf-8  -*-
#!/usr/local/bin/python

__author__ = 'jian.yao'

from django.http import HttpResponse, HttpResponseRedirect
from django.template import Context, loader
from django.utils import simplejson
from django.utils.cache import patch_response_headers
from django.shortcuts import render_to_response
from django import template
from commodity.models import Commodity
from django.db.models import Q
from backend import add_commodity, get_commodity_list
from sso.decorators import getDefaultChannel, getDoUrl
from sso.views import getDefaultUrl
from misc.logger import SysLogger

def commodity_list_view(request):
    request.CUSTOM_VARY = True
    _catagory = request.parameters.get("catagory", None)
    context = template.RequestContext(request)
    _commodity_list = get_commodity_list(_catagory)
    _commodity_count = 0
    if _commodity_list:
        _commodity_count = _commodity_list.count()

    extra_context = {
        "commodity_catagory" : _catagory,
        "commodity_count" : _commodity_count,
        "commodity_list" : _commodity_list,
    }
    context.update(extra_context)
    response = render_to_response("warehouse/commodity_list.html", context_instance=context)
    response.content_type = "text/html; charset=utf-8"
    patch_response_headers(response, 0)
    return response

def commodity_add_view(request):
    request.CUSTOM_VARY = True
    tem = loader.get_template("warehouse/commodity_add.html");
    _commodity_id = request.parameters.get("commodity_id", None);
    _dourl = getDoUrl(getDefaultChannel(), "commodity_add")
    if not _commodity_id:
        t = Context({"dourl": _dourl,
                     "commodity" : None})
    else:
        try:
            _commodity = Commodity.objects.filter(Q(id = _commodity_id))
            t = Context({"dourl": _dourl,
                        "commodity" : _commodity})
        except Commodity.DoesNotExist:
            t = Context({"dourl": _dourl,
                         "commodity" : None})
    return HttpResponse(tem.render(t))

def commodity_do_add_view(request):
    channel = request.parameters.get("channel")
    name = request.parameters.get("name")
    stock = request.parameters.get("stock")
    price = request.parameters.get("price")
    catagory = request.parameters.get("catagory")
    if((not type(eval(stock)) == int) or (not type(eval(price)) == float)):
        url = getDefaultUrl(channel, False)
        mes = u'添加商品失败的原因: 库存必须为整数，价格必须为浮点数'
        go = url + mes
        httpObj = HttpResponseRedirect(go)
        return httpObj

    desc = request.parameters.get("desc")
    result, errMes, Commodity = add_commodity(name, **{"stock": stock, "price":price, "desc":desc, "catagory":catagory})

    if (channel is None) or channel == '':
        channel = getDefaultChannel()
    if result is True:
        url = getDefaultUrl(channel, True)
        mes = u'您已经成功添加了一件商品'
        go = url + mes
        httpObj = HttpResponseRedirect(go)
    else:
        url = getDefaultUrl(channel, False)
        mes = u'添加商品失败的原因: ' + errMes
        go = url + mes
        httpObj = HttpResponseRedirect(go)

    return httpObj

def commodity_delete_view(request):
    request.CUSTOM_VARY = True
    commodity_id = request.parameters.get('commodity_id', None)
    try:
        Commodity.objects.filter(Q(id = commodity_id)).delete()
        _result = True
        _message = "Delete successfully!"
    except Exception, exp:
        _result = False
        _message = "Delete failed!"
        SysLogger.exception(exp)

    _response = {"result": _result, "message": _message}
    json = simplejson.dumps(_response)
    return HttpResponse(json, mimetype='application/json')

def commodity_edit_view(request):
    request.CUSTOM_VARY = True
    commodity_id = request.parameters.get("commodity_id", None)
    name = request.parameters.get("edit_commodity_name")
    stock = request.parameters.get("edit_commodity_stock")
    price = request.parameters.get("edit_commodity_price")
    catagory = request.parameters.get("edit_commodity_catagory")
    channel = request.parameters.get("channel")

    if((not type(eval(stock)) == int) or (not type(eval(price)) == float)):
        url = getDefaultUrl(channel, False)
        mes = u'添加商品失败的原因: 库存必须为整数，价格必须为浮点数'
        go = url + mes
        httpObj = HttpResponseRedirect(go)
        return httpObj

    desc = request.parameters.get("edit_commodity_desc")

    try:
        Commodity.objects.filter(id = commodity_id).update(name = name, stock = stock, price = price, catagory = catagory, description = desc)
    except Exception, exp:
        SysLogger.exception(exp)
    return HttpResponseRedirect("/warehouse/commodity/list")













